<template>
  <div class="app-container">
    <!-- 表单 -->
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>

      <el-table
        :data="tableData"
        :header-cell-style="{background:'#eee'}"
        border
        v-loading="loading"
        style="width: 100%;margin-bottom: 20px;"
      >
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" prop="role_name" label="名称" width="180"></el-table-column>
        <el-table-column align="center" prop="role_desc" label="角色描述"></el-table-column>
        <el-table-column align="center" prop="add_time" label="创建时间"></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              @click="handleEdite(scope.row)"
              type="text"
              size="small"
            >编辑</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="这是一段内容确定删除吗？"
              @onConfirm="handleDel(scope.row)"
            >
              <el-button
              style="margin-left:10px;color:red" slot="reference" type="text" size="small">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 右侧抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="margin-left:50px">
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="form.role_name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="role_desc">
          <el-input type="textarea" v-model="form.role_desc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <el-form-item label="权限列表" prop="act_list">
          <el-tree
            ref="tree"
            :data="treeData"
            show-checkbox
            node-key="id"
            default-expand-all
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelSub">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { getPageList } from "@/api/page";
import { getRoleList, deleteRole, addRole, editRole } from "@/api/role";
import { parseTime } from "@/utils/index";

export default {
  name: "RolePermission",
  data() {
    return {
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      // 表数据
      tableData: [],
      // 编辑抽屉
      drawer: false,
      direction: "rtl",
      title: "编辑",
      // 表单数据
      form: {
        role_name: "",
        role_desc: "",
        act_list: []
      },
      rules: {
        role_name: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        role_desc: [
          { required: true, message: "请选输入角色描述", trigger: "blur" }
        ],
        act_list: [
          { required: true, message: "请选择权限菜单", trigger: "blur" }
        ]
      },
      // 树形
      treeData: [],
      defaultProps: {
        children: "children",
        label: "root_name"
      },
      checkKeys: [],
      loading: false
    };
  },
  mounted() {
    this.getRoleList();
    this.getTreeData();
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      this.loading = true;
      const res = await getRoleList({
        page: this.currentPage.toString(),
        limit: this.pageSize.toString()
      });
      this.loading = false;
      console.log(res);
      this.tableData = res.data;
      this.tableData.forEach(item => {
        if (item.add_time == 0) {
          item.add_time = "-";
        } else {
          item.add_time = parseTime(item.add_time, "{y}-{m}-{d} {h}:{i}:{s}");
        }
      });
      this.total = res.count;
    },
    // 获取树形
    async getTreeData() {
      const res = await getPageList({
        page: "1",
        limit: "999"
      });
      this.treeData = res.data;
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current;
      this.getRoleList();
    },
    // 删除角色
    async handleDel(row) {
      console.log(row);
      try {
        const res = await deleteRole({ id: row.id });
        console.log(res);
        this.getRoleList();
        this.$message({
          message: "删除成功",
          type: "success"
        });
      } catch (error) {
        this.$message.error("删除失败");
        console.log(error);
      }
    },
    // 编辑角色
    handleEdite(row) {
      console.log(row);
      this.getTreeData();
      this.drawer = true;

      this.$nextTick(() => {
        this.$refs["tree"].setCheckedKeys(row.act_list);
      });
      const form = {
        role_name: row.role_name,
        role_desc: row.role_desc,
        act_list: row.act_list,
        id: row.id
      };
      this.form = form;
      this.title = "编辑";
    },
    // 添加角色
    addList() {
      this.getTreeData();
      this.title = "添加";
      this.drawer = true;
    },
    // 右侧抽屉
    handleClose(done) {
      this.resetForm("form");
      const form = {
        role_name: "",
        role_desc: "",
        act_list: []
      };
      this.form = form;
      done();
    },
    // 表单
    cancelSub() {
      this.resetForm("form");
      const form = {
        role_name: "",
        role_desc: "",
        act_list: []
      };
      this.form = form;
      this.drawer = false;
    },
    onSubmit() {
      this.form.act_list = this.$refs.tree.getCheckedKeys();
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.title === "添加") {
            const res = await addRole({ ...this.form });
            if (res.st === 1) {
              this.resetForm("form");
              const form = {
                role_name: "",
                role_desc: "",
                act_list: []
              };
              this.form = form;
              this.getRoleList();
              this.$message({
                message: "添加角色成功",
                type: "success"
              });
              this.drawer = false;
            } else {
              console.log(res);
            }
          } else if (this.title === "编辑") {
            const res = await editRole({ ...this.form });
            if (res.st === 1) {
              this.resetForm("form");
              const form = {
                role_name: "",
                role_desc: "",
                act_list: []
              };
              this.form = form;
              this.getRoleList();
              this.$message({
                message: "编辑角色成功",
                type: "success"
              });
              this.drawer = false;
            } else {
              console.log(res);
            }
          }
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$refs.tree.setCheckedKeys([]);
      this.drawer = false;
    }
    //树形
  }
};
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-input--medium .el-input__inner {
  width: 360px;
}
::v-deep .el-textarea__inner {
  width: 360px;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
}
</style>